package com.redlion.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.redlion.GameActivity;
import com.redlion.StartActivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class GetAllUsers extends AsyncTask<Void, Void, Void> {
	private Handler handler;
	private ProgressDialog dialog;
	private Context context;
	// private String name;
	public static String URLbody = "http://kinderstadt.w1.ms5.eu/pdd/";
	public static final String allUserURL = URLbody + "player/ranking/";
	private static final String TAG = "Server";
	static HttpParams httpParameters = new BasicHttpParams();
	static int timeoutConnection = 100000;
	static int timeoutSocket = 200000;
	Message m = new Message();
	private UserData player;
	private int ranking;

	public GetAllUsers(StartActivity startActivity, UserData player, Handler handler) {
		this.context = startActivity;
		this.handler = handler;
		this.player = player;
	}

	@Override
	protected void onPreExecute() {
		dialog = new ProgressDialog(context);
		dialog.setMessage("Update Highscore...");
		dialog.setIndeterminate(true);
		dialog.setOnCancelListener(new OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				GetAllUsers.this.cancel(true);
				Toast.makeText(context, "Update abgebrochen", Toast.LENGTH_SHORT).show();
			}
		});
		dialog.show();
	}

	@Override
	protected Void doInBackground(final Void... args) {

		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		HttpClient httpClient = new DefaultHttpClient(httpParameters);
		Log.i("Server", allUserURL + "/" + player.id + "/" + player.score + "/" + player.playtime);
		HttpGet httpGet = new HttpGet(allUserURL + "/" + player.id + "/" + player.score + "/" + player.playtime);
		HttpResponse response;
		UserData sd = null;
		m.arg1 = 1;
		try {
			httpGet.addHeader("Content-type", "application/json");
			httpGet.addHeader("Accept", "application/json");
			response = httpClient.execute(httpGet);
			// TODO: HTTP-Status (z.B. 404) in eigener Anwendung verarbeiten.

			Log.i(TAG, response.getStatusLine().toString());
			HttpEntity entity = response.getEntity();

			if (entity != null) {

				InputStream instream = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
				StringBuilder sb = new StringBuilder();

				String line = null;
				while ((line = reader.readLine()) != null)
					sb.append(line);

				String result = sb.toString();
				Log.i(TAG, result);
				instream.close();

				JSONObject json = new JSONObject(result);
				JSONObject playerData = json.getJSONObject("player");

				if (playerData != null && !playerData.isNull("ranking")) {
					ranking = playerData.getInt("ranking");
				}

				JSONArray valArray = json.getJSONArray("playerSet");

				ArrayList<UserData> userList = new ArrayList<UserData>();

				for (int i = 0; i < valArray.length(); i++) {
					JSONObject entryData = valArray.getJSONObject(i);
					int id = entryData.getInt("id");
					int score = entryData.getInt("score");
					int playtime = entryData.getInt("playtime");
					String name = entryData.getString("name");
					String location = entryData.getString("location");
					sd = new UserData(id, score, i + 1, playtime, name, location);
					userList.add(sd);
				}
				m.obj = userList;
				m.arg1 = 0;
				m.arg2 = ranking;
			}
		} catch (ClientProtocolException e) {
			m.arg1 = 1;
			Log.e("Debug", e.getMessage());
		} catch (IOException e) {
			m.arg1 = 1;
			Log.e("Debug", e.getMessage());
		} catch (Exception e) {
			m.arg1 = 1;
			if (e.getMessage() != null)
				Log.e("Debug", e.getMessage());
		}
		return null;
	}

	@Override
	protected void onPostExecute(final Void unused) {
		handler.sendMessage(m);
		dialog.dismiss();
	}

}
